package org.damazio.bhtranscams;

import android.app.TabActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.AdapterView.OnItemClickListener;

/**
 * Main activity which shows a tabbed screen with both the location list and its
 * map.
 * 
 * @author rdamazio
 */
public class BHTransCams extends TabActivity implements OnItemClickListener {
  private static final double MAX_CLOSEST_DISTANCE_KM = 50;
  private static final double MAX_CLOSEST_DISTANCE_DEGREES = MAX_CLOSEST_DISTANCE_KM * 0.5399568 * 50;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Drawable listIcon = getResources().getDrawable(android.R.drawable.ic_menu_sort_alphabetically);
    Drawable mapIcon = getResources().getDrawable(android.R.drawable.ic_menu_mapmode);

    // Create the tabs
    TabHost tabHost = getTabHost();
    tabHost.addTab(tabHost.newTabSpec("list_tab")
        .setIndicator(getString(R.string.listTab), listIcon)
        .setContent(R.id.listview));
    tabHost.addTab(tabHost.newTabSpec("map_tab")
        .setIndicator(getString(R.string.mapTab), mapIcon)
        .setContent(new Intent(this, CamerasMap.class)));

    // Populate the list
    ArrayAdapter<Cameras> adapter = new ArrayAdapter<Cameras>(this,
        android.R.layout.simple_list_item_1, Cameras.values());
    ListView camerasListView = (ListView) findViewById(R.id.listview);
    camerasListView.setAdapter(adapter);
    camerasListView.setTextFilterEnabled(true);
    camerasListView.setOnItemClickListener(this);

    // Select the first tab
    tabHost.setCurrentTab(0);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Load the menu
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_menu, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.about:
        startActivity(new Intent(this, BHTransCamsAbout.class));
        break;
      case R.id.closestCam: {
        ClosestCameraPicker cameraPicker = new ClosestCameraPicker(this, MAX_CLOSEST_DISTANCE_DEGREES);
        cameraPicker.showClosestCameraToLocation();
        break;
      }
    }
    return true;
  }

  /**
   * Callback when a list item is clicked.
   */
  public void onItemClick(AdapterView<?> l, View v, int position, long id) {
    Cameras camera = (Cameras) l.getAdapter().getItem(position);
    BHTransCamView.startCameraViewActivity(this, camera);
  }
}